@rendermode InteractiveServer
@using DaoHang.Services
@using DaoHang.Models
@using DaoHang.Components.Shared
@inject IWebsiteService WebsiteService
@inject ICategoryService CategoryService
@inject IWebsiteInfoService WebsiteInfoService
@inject IAliCloudAIService AliCloudAIService
@inject IJSRuntime JSRuntime

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="bi bi-globe me-2"></i>网站管理
        </h5>
        <button class="btn btn-primary btn-sm" @onclick="ShowAddWebsiteModal">
            <i class="bi bi-plus-lg me-1"></i>添加网站
        </button>
    </div>
    <div class="card-body">
        @if (isLoadingWebsites)
        {
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2">加载中...</p>
            </div>
        }
        else if (websites.Any())
        {
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>网站信息</th>
                            <th>分类</th>
                            <th>排序</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var website in websites)
                        {
                            <tr>
                                <td class="align-middle">
                                    <div class="d-flex align-items-center">
                                        <div class="me-3">
                                            <WebsiteIcon IconUrl="@website.IconUrl" 
                                                        AltText="@website.Name" 
                                                        CssClass="table-icon" />
                                        </div>
                                        <div>
                                            <div class="fw-bold">@website.Name</div>
                                            <small class="text-muted">
                                                <a href="@website.Url" target="_blank" class="text-decoration-none">
                                                    @(website.Url.Length > 50 ? website.Url.Substring(0, 50) + "..." : website.Url)
                                                </a>
                                            </small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge bg-secondary">@website.Category.Name</span>
                                </td>
                                <td>@website.SortOrder</td>
                                <td>@website.CreateTime.ToString("yyyy-MM-dd")</td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-primary" 
                                                @onclick="() => EditWebsite(website)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-outline-danger" 
                                                @onclick="() => DeleteWebsite(website.Id)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        }
        else
        {
            <div class="text-center py-4 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-2">暂无网站数据</p>
            </div>
        }
    </div>
</div>

<!-- 添加/编辑网站模态框 -->
@if (showModal)
{
    <div class="modal-backdrop fade show" @onclick="HideModal"></div>
    <div class="modal fade show" style="display: block; z-index: 1051;" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        @(isEditingWebsite ? "编辑网站" : "添加网站")
                    </h5>
                    <button type="button" class="btn-close" @onclick="HideModal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <!-- URL输入区域 -->
                        <div class="col-md-12 mb-4">
                            <div class="card border-primary">
                                <div class="card-header bg-primary text-white">
                                    <h6 class="mb-0"><i class="bi bi-link-45deg me-2"></i>网站地址</h6>
                                </div>
                                <div class="card-body">
                                    <div class="input-group mb-3">
                                        <span class="input-group-text"><i class="bi bi-globe"></i></span>
                                        <input type="url" class="form-control" placeholder="请输入网站URL，如：https://www.example.com" 
                                               @bind="currentWebsite.Url" required />
                                        <button class="btn btn-success" type="button" @onclick="GetWebsiteInfo" disabled="@isGettingInfo">
                                            @if (isGettingInfo)
                                            {
                                                <span class="spinner-border spinner-border-sm me-1"></span>
                                                <span>获取中...</span>
                                            }
                                            else
                                            {
                                                <i class="bi bi-download me-1"></i>
                                                <span>一键获取信息</span>
                                            }
                                        </button>
                                    </div>
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle me-1"></i>
                                        点击"一键获取信息"可自动填充网站名称、描述和图标
                                    </small>
                                </div>
                            </div>
                        </div>

                        <!-- 基本信息区域 -->
                        <div class="col-md-6 mb-4">
                            <div class="card border-info">
                                <div class="card-header bg-info text-white">
                                    <h6 class="mb-0"><i class="bi bi-info-square me-2"></i>基本信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label class="form-label">网站名称 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" @bind="currentWebsite.Name" required />
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">网站图标URL</label>
                                        <div class="input-group">
                                            <input type="url" class="form-control" @bind="currentWebsite.IconUrl" />
                                            @if (!string.IsNullOrEmpty(currentWebsite.IconUrl))
                                            {
                                                <span class="input-group-text">
                                                    <WebsiteIcon IconUrl="@currentWebsite.IconUrl" 
                                                                AltText="图标预览" 
                                                                CssClass="preview-icon" />
                                                </span>
                                            }
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">分类 <span class="text-danger">*</span></label>
                                        <select class="form-select" @bind="currentWebsite.CategoryId" required>
                                            <option value="0">请选择分类</option>
                                            @foreach (var category in categories)
                                            {
                                                <option value="@category.Id">@category.Name</option>
                                            }
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">排序权重</label>
                                        <input type="number" class="form-control" @bind="currentWebsite.SortOrder" min="0" />
                                        <small class="text-muted">数字越小排序越靠前</small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 描述信息区域 -->
                        <div class="col-md-6 mb-4">
                            <div class="card border-warning">
                                <div class="card-header bg-warning text-dark">
                                    <h6 class="mb-0"><i class="bi bi-chat-quote me-2"></i>描述信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label class="form-label">网站描述</label>
                                        <div class="position-relative">
                                            <textarea class="form-control" rows="4" @bind="currentWebsite.Description" 
                                                      placeholder="简要描述网站的功能和特色..."></textarea>
                                            <button class="btn btn-success btn-sm position-absolute top-0 end-0 m-2" 
                                                    type="button" @onclick="GenerateAIDescription" disabled="@isGeneratingAI">
                                                @if (isGeneratingAI)
                                                {
                                                    <span class="spinner-border spinner-border-sm me-1"></span>
                                                    <span>生成中...</span>
                                                }
                                                else
                                                {
                                                    <i class="bi bi-robot me-1"></i>
                                                    <span>AI总结</span>
                                                }
                                            </button>
                                        </div>
                                        <small class="text-muted">
                                            <i class="bi bi-info-circle me-1"></i>
                                            点击"AI总结"可根据网站内容自动生成描述
                                        </small>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">关键词标签</label>
                                        <input type="text" class="form-control" @bind="currentWebsite.Tags" 
                                               placeholder="关键词之间用逗号分隔，如：搜索,工具,在线" />
                                    </div>

                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="isRecommended" 
                                                   @bind="currentWebsite.IsRecommended">
                                            <label class="form-check-label" for="isRecommended">
                                                <i class="bi bi-star-fill text-warning me-1"></i>
                                                设为推荐网站
                                            </label>
                                        </div>
                                        <small class="text-muted">
                                            推荐的网站将会在相关分类中被优先展示
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="HideModal">取消</button>
                    <button type="button" class="btn btn-primary" @onclick="SaveWebsite">保存</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    /// <summary>
    /// 网站数据列表
    /// </summary>
    private List<Website> websites = new List<Website>();

    /// <summary>
    /// 分类数据列表
    /// </summary>
    private List<Category> categories = new List<Category>();

    /// <summary>
    /// 当前正在编辑的网站
    /// </summary>
    private Website currentWebsite = new Website();

    /// <summary>
    /// 是否正在加载网站数据
    /// </summary>
    private bool isLoadingWebsites = true;

    /// <summary>
    /// 是否正在编辑网站（区分添加和编辑模式）
    /// </summary>
    private bool isEditingWebsite = false;

    /// <summary>
    /// 是否正在获取网站信息
    /// </summary>
    private bool isGettingInfo = false;

    /// <summary>
    /// 是否正在生成AI描述
    /// </summary>
    private bool isGeneratingAI = false;

    /// <summary>
    /// 是否显示模态框
    /// </summary>
    private bool showModal = false;

    /// <summary>
    /// 组件初始化时加载数据
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await LoadWebsitesAsync();
        await LoadCategoriesAsync();
    }

    /// <summary>
    /// 加载网站数据
    /// </summary>
    private async Task LoadWebsitesAsync()
    {
        isLoadingWebsites = true;
        try
        {
            websites = await WebsiteService.GetAllWebsitesAsync();
        }
        catch (Exception)
        {
            // 处理异常
            websites = new List<Website>();
        }
        finally
        {
            isLoadingWebsites = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 加载分类数据
    /// </summary>
    private async Task LoadCategoriesAsync()
    {
        try
        {
            categories = await CategoryService.GetAllCategoriesAsync();
        }
        catch (Exception)
        {
            // 处理异常
            categories = new List<Category>();
        }
    }

    /// <summary>
    /// 显示添加网站的模态框
    /// </summary>
    private void ShowAddWebsiteModal()
    {
        isEditingWebsite = false;
        currentWebsite = new Website
        {
            CreateTime = DateTime.Now,
            SortOrder = 0
        };
        showModal = true;
        StateHasChanged();
    }

    /// <summary>
    /// 编辑网站信息
    /// </summary>
    private void EditWebsite(Website website)
    {
        isEditingWebsite = true;
        currentWebsite = new Website
        {
            Id = website.Id,
            Name = website.Name,
            Url = website.Url,
            Description = website.Description,
            IconUrl = website.IconUrl,
            CategoryId = website.CategoryId,
            SortOrder = website.SortOrder,
            Tags = website.Tags,
            IsRecommended = website.IsRecommended,
            CreateTime = website.CreateTime
        };
        showModal = true;
        StateHasChanged();
    }

    /// <summary>
    /// 删除网站
    /// </summary>
    private async Task DeleteWebsite(int id)
    {
        bool confirmed = await JSRuntime.InvokeAsync<bool>("confirm", "确定要删除这个网站吗？");
        if (confirmed)
        {
            await WebsiteService.DeleteWebsiteAsync(id);
            await LoadWebsitesAsync();
        }
    }

    /// <summary>
    /// 获取网站信息
    /// </summary>
    private async Task GetWebsiteInfo()
    {
        if (string.IsNullOrWhiteSpace(currentWebsite.Url))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先输入网站URL");
            return;
        }

        isGettingInfo = true;
        try
        {
            var info = await WebsiteInfoService.GetWebsiteInfoAsync(currentWebsite.Url);
            if (info != null)
            {
                currentWebsite.Name = info.Title ?? currentWebsite.Name;
                currentWebsite.Description = info.Description ?? currentWebsite.Description;
                currentWebsite.IconUrl = info.IconUrl ?? currentWebsite.IconUrl;
            }
        }
        catch (Exception)
        {
            await JSRuntime.InvokeVoidAsync("alert", "获取网站信息失败，请手动填写");
        }
        finally
        {
            isGettingInfo = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 生成AI描述
    /// </summary>
    private async Task GenerateAIDescription()
    {
        if (string.IsNullOrWhiteSpace(currentWebsite.Url))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先输入网站URL");
            return;
        }

        if (string.IsNullOrWhiteSpace(currentWebsite.Name))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先输入网站名称");
            return;
        }

        isGeneratingAI = true;
        try
        {
            var description = await AliCloudAIService.GenerateWebsiteDescriptionAsync(
                currentWebsite.Name, 
                currentWebsite.Url
            );
            currentWebsite.Description = description;
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"生成网站描述失败：{ex.Message}");
        }
        finally
        {
            isGeneratingAI = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 保存网站信息
    /// </summary>
    private async Task SaveWebsite()
    {
        // 表单验证
        if (string.IsNullOrWhiteSpace(currentWebsite.Name))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请输入网站名称");
            return;
        }

        if (string.IsNullOrWhiteSpace(currentWebsite.Url))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请输入网站URL");
            return;
        }

        if (currentWebsite.CategoryId <= 0)
        {
            await JSRuntime.InvokeVoidAsync("alert", "请选择网站分类");
            return;
        }

        try
        {
            // 先保存网站基本信息，不等待图标下载
            if (isEditingWebsite)
            {
                await WebsiteService.UpdateWebsiteAsync(currentWebsite);
            }
            else
            {
                // 添加网站时使用快速方法立即保存基本信息
                await WebsiteService.AddWebsiteQuickAsync(currentWebsite);
            }

            // 立即关闭模态框，提升用户体验
            showModal = false;
            
            // 立即重新加载数据显示新添加的网站
            await LoadWebsitesAsync();

            // 如果是新添加的网站且没有用户指定的图标URL，在后台异步下载图标
            if (!isEditingWebsite && string.IsNullOrWhiteSpace(currentWebsite.IconUrl))
            {
                // 后台异步下载图标，不阻塞用户操作
                _ = Task.Run(async () =>
                {
                    try
                    {
                        // 使用网站服务的后台图标下载功能
                        await WebsiteService.UpdateWebsiteIconAsync(currentWebsite.Url);
                        
                        // 下载完成后刷新页面显示新图标（可选）
                        await InvokeAsync(async () =>
                        {
                            await LoadWebsitesAsync();
                            StateHasChanged();
                        });
                    }
                    catch (Exception)
                    {
                        // 静默处理图标下载失败，不影响用户操作
                        // 网站已经成功保存，图标下载失败不是致命错误
                    }
                });
            }
        }
        catch (Exception)
        {
            await JSRuntime.InvokeVoidAsync("alert", "保存网站信息失败，请重试");
        }
    }

    /// <summary>
    /// 隐藏模态框
    /// </summary>
    private void HideModal()
    {
        showModal = false;
        StateHasChanged();
    }
} 